package cn.ycq.im.commons.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.Map;

public abstract class Https {

    public static class ResponseUtils{

        public static void writeJSONByObject(FullHttpResponse response, Object obj){
            writeJSON(response,JsonUtils.objectToJson(obj));
        }

        public static void writeJSON(FullHttpResponse response, String json){
            response.headers().set("Content-Type","application/json;charset=utf-8");

            ByteBuf byteBuf = Unpooled.copiedBuffer(json.getBytes());
            response.content().writeBytes(byteBuf);
        }

        public static void writeHtml(FullHttpResponse response, String html){
            response.headers().set("Content-Type","text/html;charset=utf-8");

            ByteBuf byteBuf = Unpooled.copiedBuffer(html.getBytes());
            response.content().writeBytes(byteBuf);
        }
    }

    public static class RequestUtils{

        public static Map<String, List<String>> getRequestParams(HttpRequest httpRequest) {
            QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
            Map<String, List<String>> parameters = decoder.parameters();
            return parameters;
        }

        public static byte[] getRequestBody(FullHttpRequest httpRequest) {
            ByteBuf byteBuf = httpRequest.content();

            byte[] buff = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buff);

            return buff;
        }

        public static String getRequestBodyToString(FullHttpRequest httpRequest) {
            return  httpRequest.content().toString(CharsetUtil.UTF_8);
        }
    }

}
